<template>
  <el-container style="height: 100%; padding: 12px 12px 0">
    <el-aside width="220px" style="background-color: white; padding: 2px; margin-bottom: 0">
      <dept-project @selectBuilding="getCurrentProject" />
    </el-aside>
    <el-main style="padding: 0 0 0 20px">
      <el-form ref="queryForm" :model="queryParams" size="mini" inline style="white-space: nowrap; overflow-x: auto" @submit.native.prevent>
        <el-form-item>
          <el-input v-model="currTableName" placeholder="请输入工序名称" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item>
          <el-button size="mini" type="primary" @click="$refs.BatchAdd.open(currentBuilding, list)" v-hasPermi="['cq:checkConfig:add']">引入工序</el-button>
          <el-button size="mini" type="primary" @click="$refs.BatchByBuildIds.open(currentBuilding)" v-hasPermi="['cq:checkConfig:add']">批量引入</el-button>
          <el-button size="mini" type="danger" icon="el-icon-delete" :disabled="listLoading" :loading="removeLoading" @click="btnRemoveBatch" v-hasPermi="['cq:checkConfig:remove']">{{ selected.length > 1 ? '批量' : '' }}删除</el-button>
        </el-form-item>
      </el-form>

      <el-table
        ref="table"
        v-loading="listLoading"
        :data="filteredList"
        size="small"
        highlight-current-row
        :height="showStandard ? 'calc((100% - 70px) * 0.6)' : 'calc(100% - 50px)'"
        style="min-height: 300px"
        @selection-change="onSelect"
        @current-change="handleCurrentChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="序号" type="index" width="50" />
        <el-table-column label="工程项目" prop="projectName" show-overflow-tooltip min-width="120" />
        <el-table-column label="楼栋" prop="buildingName" show-overflow-tooltip min-width="80" />
        <el-table-column label="阶段" prop="checktypeName" show-overflow-tooltip min-width="200" />
        <el-table-column label="工序" prop="checktableName" show-overflow-tooltip min-width="300" />
        <el-table-column label="验收对象" prop="unitTypeName" align="center" min-width="80" />
        <el-table-column label="工程师验收比例（%）" prop="gcsPercent" align="center" min-width="120" />
        <el-table-column label="监理验收比例（%）" prop="jlPercent" align="center" min-width="120" />
        <el-table-column label="项目总验收比例（%）" prop="xmzPercent" align="center" min-width="120" />
        <el-table-column label="项目经理验收比例（%）" prop="xmjlPercent" align="center" min-width="130" />
        <el-table-column label="专业类别" align="center" min-width="70">
          <dict-tag slot-scope="{ row }" :options="specialTypes" :value="row.specialTypeId" />
        </el-table-column>
        <el-table-column label="报验是否上传附件" align="center" min-width="130">
          <el-tag slot-scope="{ row }" size="small" :type="row.isReqAttch ? 'primary' : 'info'">{{ row.isReqAttch ? '是' : '否' }}</el-tag>
        </el-table-column>
        <el-table-column label="是否启用" align="center" min-width="80">
          <el-tag slot-scope="{ row }" size="small" :type="row.isEnable ? 'primary' : 'info'">{{ row.isEnable ? '是' : '否' }}</el-tag>
        </el-table-column>
        <el-table-column label="操作" fixed="right" align="center" width="120">
          <div slot-scope="{ row }" style="text-align: left" @click.stop>
            <el-button size="mini" type="text" icon="el-icon-edit" @click="$refs.EditCheckConfig.open(row)" v-hasPermi="['cq:checkConfig:edit']">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" :loading="row.removeLoading" @click="btnRemoveItem(row)" v-hasPermi="['cq:checkConfig:remove']">删除</el-button>
          </div>
        </el-table-column>
      </el-table>
      <StandardList ref="StandardList" />
    </el-main>
    <EditCheckConfig ref="EditCheckConfig" v-model="showEditCheckConfig" @ok="getList" />
    <BatchAdd ref="BatchAdd" v-model="showBatchAdd" @ok="getList" />
    <BatchByBuildIds ref="BatchByBuildIds" v-model="showBatchByBuildIds" @ok="getList" />
  </el-container>
</template>
<script>
// 工程质量-楼栋工序配置页面
import { debounce } from '@/utils'
import { getSpecialTypes } from '@/utils/dict/custom'
import { listCheckConfig, delCheckConfig, delCheckConfigBetch } from '@/api/qualityManage/cq'
import DeptProject from '@/views/qualityManage/components/DeptProject'
import EditCheckConfig from './BuildingProcess/EditCheckConfig'
import BatchAdd from './BuildingProcess/BatchAddCheckConfig'
import BatchByBuildIds from './BuildingProcess/BatchByBuildIds'
import StandardList from './BuildingProcess/CheckConfigStandardList'
export default {
  name: 'CheckConfig',
  components: { DeptProject, EditCheckConfig, BatchAdd, BatchByBuildIds, StandardList },
  data() {
    return {
      listLoading: false,
      list: [],
      queryParams: { buildingId: '' },
      currTableName: '',
      currentBuilding: {},
      selected: [],
      removeLoading: false,
      showEditCheckConfig: false,
      showBatchAdd: false,
      showBatchByBuildIds: false,
      specialTypes: [], // 专业类别
      showStandard: false // 显示验收标准
    }
  },
  computed: {
    filteredList() {
      // 楼栋工序, 本地过滤
      const name = this.currTableName.toLowerCase().trim()
      return this.list.filter(i => {
        const like_name = name ? i.checktableName.toLowerCase().includes(name) : true
        return like_name
      })
    }
  },
  watch: {
    filteredList: {
      deep: true,
      handler(val) {
        if (!val?.length) return
        this.$refs.table.setCurrentRow(val[0])
      }
    }
  },
  created() {
    this.btnRemoveItem = debounce(this.removeItem, 1e3, true)
    this.btnRemoveBatch = debounce(this.removeBatch, 1e3, true)
    getSpecialTypes().then(res => (this.specialTypes = res))
  },
  methods: {
    getCurrentProject(data) {
      this.currentBuilding = data
      if (!data?.id) return (this.list = [])
      this.queryParams.buildingId = data.id
      this.getList()
    },
    // 楼栋工序列表
    async getList() {
      if (!this.queryParams.buildingId) return this.$message.warning('请选择楼栋')

      this.listLoading = true
      const res = await listCheckConfig(this.queryParams).catch(() => false)
      this.listLoading = false
      if (res === false) return

      const data = res.data || []
      data.map(i => (i.removeLoading = false))
      this.list = data
      this.$refs.table.setCurrentRow(data[0])
      this.handleCurrentChange(data[0])
    },
    onSelect(val) {
      this.selected = val
    },
    handleCurrentChange(item) {
      const show = !!item?.configId
      this.showStandard = show
      // 获取或重置验收标准
      show ? this.$refs.StandardList?.open(item) : this.$refs.StandardList?.reset()
    },
    async removeItem(item) {
      if (item.removeLoading) return
      const res1 = await this.$confirm(`确定删除工序：${item.checktableName}?`, '警告', { type: 'warning' }).catch(() => false)
      if (res1 !== 'confirm') return

      item.removeLoading = true
      const res = await delCheckConfig(item.configId).catch(() => false)
      item.removeLoading = false
      if (res === false) return

      this.msgSuccess('删除成功')
      this.getList()
    },
    async removeBatch() {
      if (this.removeLoading) return
      const { selected } = this
      const len = selected.length
      if (!len) return this.$message.warning('请先选择工序')
      const names = selected.map(i => i.checktableName).join('、')
      const shortMsg = names.length > 255 ? `${names.substring(0, 255)}...` : names
      const res1 = await this.$confirm(len > 1 ? `确定批量删除选中的${len}个工序：${shortMsg}？` : `确定删除工序：${shortMsg}？`, { type: 'warning' }).catch(() => false)
      if (res1 !== 'confirm') return

      this.removeLoading = true
      const ids = selected.map(i => i.configId).join(',')
      const res = await delCheckConfigBetch(ids).catch(() => false)
      this.removeLoading = false
      if (res === false) return

      this.msgSuccess('删除成功')
      this.$refs.table.clearSelection()
      // this.handleCurrentChange()
      this.getList()
    }
  }
}
</script>
